#include "Projectiles.h"
#include "../SGD Wrappers/SGD_GraphicsManager.h"
#include "DestroyEntityMessage.h"
#include "GamePlayState.h"
#include <sstream>
#include "Player.h"
#include "Game.h"

Projectiles::Projectiles()
{

}


Projectiles::~Projectiles()
{
	SetOwner(nullptr);
}

void Projectiles::SetOwner(Entity* o)
{
	if (nullptr != owner)
		owner->Release();

	owner = o;

	if (nullptr != owner)
		owner->AddRef();
}

void Projectiles::Update(float elapsedTime)
{
	SGD::Rectangle camOffset{ { Game::GetInstance()->GetCameraPos().x - 100,
		Game::GetInstance()->GetCameraPos().y - 100 },
		SGD::Size{ (Game::GetInstance()->GetScreenWidth() + 500) / Game::GetInstance()->GetZoomLevel(),
		(Game::GetInstance()->GetScreenHeight() + 500) / Game::GetInstance()->GetZoomLevel() } };
	SGD::Rectangle posRect = { this->GetRect().ComputeCenter(), SGD::Size{ 1, 1 } };
	if (camOffset.IsIntersecting(posRect))
	{
		collisionFlag = 0;
		SGD::Vector distance = owner->GetPosition() - position;
		float length = distance.ComputeLength();
		if (length > 400)
		{
			DestroyEntityMessage* msg = new DestroyEntityMessage(this);
			msg->QueueMessage();
			msg = nullptr;
		}
		Entity::Update(elapsedTime);
	}
	else
		collisionFlag = -1;
}

void Projectiles::Render(void)
{
	SGD::Rectangle camOffset{ { Game::GetInstance()->GetCameraPos().x - 100,
		Game::GetInstance()->GetCameraPos().y - 100 },
		SGD::Size{ (Game::GetInstance()->GetScreenWidth() + 500) / Game::GetInstance()->GetZoomLevel(),
		(Game::GetInstance()->GetScreenHeight() + 500) / Game::GetInstance()->GetZoomLevel() } };
	SGD::Rectangle posRect = { this->GetRect().ComputeCenter(), SGD::Size{ 1, 1 } };
	if (camOffset.IsIntersecting(posRect))
	{
		SGD::Rectangle rect =
		{ SGD::Point{ position.x - Game::GetInstance()->GetCameraPos().x,
		position.y - Game::GetInstance()->GetCameraPos().y }, size };
		/*SGD::GraphicsManager::GetInstance()->DrawRectangle(
			rect, SGD::Color{ 255, 255, 255 });*/
		
	}
}

void Projectiles::HandleCollision(const IEntity* other)
{
	if (owner != other && (other->GetType() != ENT_PLANET ))
	{
		DestroyEntityMessage* msg = new DestroyEntityMessage(this);
		msg->QueueMessage();
		msg = nullptr;
	}
	
}